package com.glory.brepda.activity.lanjian;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.util.Size;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.Constant;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;

public class MlotGoldFingerFixOrChangeActivity extends BaseActivity {

    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvWHereType)
    TextView tvWhereType;
    @BindView(R.id.ivWhereArrow)
    ImageView ivWhereArrow;
    @BindView(R.id.flWhereList)
    FrameLayout flWhereList;
    @BindView(R.id.tvStepNameType)
    TextView tvStepNameType;
    @BindView(R.id.ivStepNameArrow)
    ImageView ivStepNameArrow;
    @BindView(R.id.flStepNameList)
    FrameLayout flStepNameList;
    @BindView(R.id.tvResonType)
    TextView tvResonType;
    @BindView(R.id.ivResonArrow)
    ImageView ivResonArrow;
    @BindView(R.id.flResonList)
    FrameLayout flResonList;
    @BindView(R.id.tvdoType)
    TextView tvdoType;
    @BindView(R.id.ivdoArrow)
    ImageView ivdoArrow;
    @BindView(R.id.fldoList)
    FrameLayout fldoList;
    @BindView(R.id.one)
    LinearLayout one;
    @BindView(R.id.two)
    LinearLayout two;
    @BindView(R.id.tvFix)
    TextView tvFix;
    @BindView(R.id.tvChange)
    TextView tvChange;
    @BindView(R.id.tvMmtType)
    TextView tvMmtType;
    @BindView(R.id.ivmmtArrow)
    ImageView ivmmtArrow;
    @BindView(R.id.flMmtList)
    FrameLayout flMmtList;
    @BindView(R.id.tvtypeType)
    TextView tvtypeType;
    @BindView(R.id.ivtypeArrow)
    ImageView ivtypeArrow;
    @BindView(R.id.fltypetList)
    FrameLayout fltypetList;
    @BindView(R.id.tvchangeType)
    TextView tvchangeType;
    @BindView(R.id.ivchangeArrow)
    ImageView ivchangeArrow;
    @BindView(R.id.flchangeList)
    FrameLayout flchangeList;
    @BindView(R.id.tvOldType)
    TextView tvOldType;
    @BindView(R.id.ivOldArrow)
    ImageView ivOldArrow;
    @BindView(R.id.flOldList)
    FrameLayout flOldList;
    @BindView(R.id.etnum)
    EditText etnum;
    @BindView(R.id.etTime)
    FreeUI_ClearEditText etTime;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;
    @BindView(R.id.eteqp)
    FreeUI_ClearEditText eteqp;
    @BindView(R.id.ettime)
    FreeUI_ClearEditText ettime;
    @BindView(R.id.ivshow)
    ImageView ivshow;

    private FreeUI_GeneralPop codePop_where,codePop_stepName,codePop_reson,codePop_do,codePop_mmt,codePop_type,codePop_change,codePop_old;
    private boolean status = false;
    private List<String> where_list = new ArrayList<>(Arrays.asList("编带工位","排出工位","测试站1工位","测试站2工位","测试站3工位","测试站4工位","卫星工位","旋转1工位","旋转2工位", "3D工位","极性工位","分类工位")) ;
    //编带工位
    private List<String> stepName_list1 = new ArrayList<>(Arrays.asList("封刀","温控器","热电偶","编带气缸","编带前后左右位置","编带上下真空","编带产品识别感应器","编带盖板","载带感应器", "编带检测灯光","压焊头底座","收料马达",
            "Z轴滑块","Z轴感应器","Z轴马达","Z轴下压位置","破真空电磁阀","同步轮及同步轮马达","走带皮带","压痕")) ;
    //排出工位
    private List<String> stepName_list2 = new ArrayList<>(Arrays.asList("阻挡片","排出滑块","敲打气缸","导轨盖板","排出感应器","排出位置左右前后高低","导轨吹气",
            "排出Z轴感应器及下压位置","排出吸嘴","真空吹气","电磁阀","离子风机")) ;
    //测试站1234工位
    private List<String> stepName_list3 = new ArrayList<>(Arrays.asList("测试片","测试座高度左右","测试定位夹","Z轴感应器","Z轴下压","Z轴马达")) ;
    //卫星工位
    private List<String> stepName_list4 = new ArrayList<>(Arrays.asList("上下电磁阀","产品识别感应器","左右前后位置","卫星盘","摄像头","Z轴马达","Z轴下压","Z轴滑块","Z轴感应器", "印章影像检测灯光")) ;
    //旋转12工位
    private List<String> stepName_list5 = new ArrayList<>(Arrays.asList("Z轴马达","Z轴下压","Z轴滑块","Z轴感应器","定位器","旋转位置")) ;
    //3D工位
    private List<String> stepName_list6 = new ArrayList<>(Arrays.asList("3D影像","Z轴马达","Z轴下压","Z轴滑块","Z轴感应器")) ;
    //极性工位
    private List<String> stepName_list7 = new ArrayList<>(Arrays.asList("极性簧片","极性影像","极性电压","Z轴马达","Z轴下压","Z轴滑块","Z轴感应器","方向判定学习")) ;
    //分类工位
    private List<String> stepName_list8 = new ArrayList<>(Arrays.asList("分类桶位置","皮带","桶感应器","分类电磁阀","吹气流量")) ;
    //主工作台
    private List<String> stepName_list9 = new ArrayList<>(Arrays.asList("吸嘴","支架","气管")) ;
    // 更换的封装
    private List<String>  mmt_list = new ArrayList<>(Arrays.asList("SOT23","SOT23-3","SOT23-5","SOT23-6","SOD-123","SOD-323","SOP-7","SOP-8","ESOP-8","DFN1X1",
            "DFN2X2","DFN2X3","DFN3X3","DFN4X4","DFN5X6","DFN8X8","DFN0603","SMA","SSOP16","SOT363","SOT323","PDFN3X2","PDFN3X3","PDFN5X6","DFN1.6X1.6","TO252",
            "TO263","SOT-89","DFN1006")) ;

    private String[] size = new String[]{"site1()","site2()","site3()","site4()","site5()","site6()","site7()","site8()"};
    private boolean[] size_bool = new boolean[]{false,false,false,false,false,false,false,false};
    private  String SIZE = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_mlot_gold_finger_fix_or_change;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        setMainLayout(llMain);

        one.setVisibility(View.VISIBLE);
        two.setVisibility(View.GONE);

        String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()).toString() ;
        etTime.setText(date);

        //调试部位
        flWhereList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(tvStepNameType != null || StringUtils.isNotEmpty(tvStepNameType.getText())){
                    tvStepNameType.setText(null);
                }

                if (codePop_where != null) {
                    if (codePop_where.isShowing()) {
                        codePop_where.dismiss();
                    }
                } else {
                    codePop_where = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flWhereList.getWidth(), where_list, ivWhereArrow, (ty, i) -> {
                        tvWhereType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivWhereArrow);
                codePop_where.showAsDropDown(flWhereList, 0, 0);
            }
        });
        //工位选择
        flStepNameList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(StringUtils.isEmpty(tvWhereType.getText())){
                    showToast("请先选择测试部位",false);
                }
                List<String> show_stepName = null;
                if(StringUtils.equals("编带工位",tvWhereType.getText())){
                    show_stepName=stepName_list1;
                }else if(StringUtils.equals("排出工位",tvWhereType.getText())){
                    show_stepName=stepName_list2;
                }else if(tvWhereType.getText().toString().contains("测试站")){
                    show_stepName=stepName_list3;
                }else if(StringUtils.equals("卫星工位",tvWhereType.getText())){
                    show_stepName=stepName_list4;
                }else if(tvWhereType.getText().toString().contains("旋转")){
                    show_stepName=stepName_list5;
                }else if(StringUtils.equals("3D工位",tvWhereType.getText())){
                    show_stepName=stepName_list6;
                }else if(StringUtils.equals("极性工位",tvWhereType.getText())){
                    show_stepName=stepName_list7;
                }else if(StringUtils.equals("分类工位",tvWhereType.getText())){
                    show_stepName=stepName_list8;
                }else{
                    show_stepName=stepName_list9;
                }

//                if (codePop_stepName != null) {
//                    if (codePop_stepName.isShowing()) {
//                        codePop_stepName.dismiss();
//                    }
//                } else {
                    codePop_stepName = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStepNameList.getWidth(), show_stepName, ivStepNameArrow, (ty, i) -> {
                        tvStepNameType.setText(ty);
//                        Toast.makeText(getApplicationContext(),ty,Toast.LENGTH_SHORT).show();
                    });
//                }
                FreeApi_PopUtils.setArrowShow(ivStepNameArrow);
                codePop_stepName.showAsDropDown(flStepNameList, 0, 0);
            }
        });

        //调试原因
        flResonList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (codePop_reson != null) {
                    if (codePop_reson.isShowing()) {
                        codePop_reson.dismiss();
                    }
                } else {
                    codePop_reson = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flResonList.getWidth(), new ArrayList<>(Arrays.asList("故障报警","主动操作")), ivResonArrow, (ty, i) -> {
                        tvResonType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivResonArrow);
                codePop_reson.showAsDropDown(flResonList, 0, 0);
            }
        });

        //调试操作
        fldoList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (codePop_do != null) {
                    if (codePop_do.isShowing()) {
                        codePop_do.dismiss();
                    }
                } else {
                    codePop_do = FreeApi_PopUtils.getNormalPop(getApplicationContext(), fldoList.getWidth(), new ArrayList<>(Arrays.asList("更换","调试","断电重启","清洁保养")), ivdoArrow, (ty, i) -> {
                        tvdoType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivdoArrow);
                codePop_do.showAsDropDown(fldoList, 0, 0);
            }
        });

        //封装
        flMmtList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (codePop_mmt != null) {
                    if (codePop_mmt.isShowing()) {
                        codePop_mmt.dismiss();
                    }
                } else {
                    codePop_mmt = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flMmtList.getWidth(),mmt_list, ivmmtArrow, (ty, i) -> {
                        tvMmtType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivmmtArrow);
                codePop_mmt.showAsDropDown(flMmtList, 0, 0);
            }
        });

        //测试片的类型
        fltypetList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (codePop_type != null) {
                    if (codePop_type.isShowing()) {
                        codePop_type.dismiss();
                    }
                } else {
                    codePop_type = FreeApi_PopUtils.getNormalPop(getApplicationContext(), fltypetList.getWidth(),new ArrayList<>(Arrays.asList("SOCKET","测试针","簧片")), ivtypeArrow, (ty, i) -> {
                        tvtypeType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivtypeArrow);
                codePop_type.showAsDropDown(fltypetList, 0, 0);
            }
        });

        //更换原因
        flchangeList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (codePop_change != null) {
                    if (codePop_change.isShowing()) {
                        codePop_change.dismiss();
                    }
                } else {
                    codePop_change = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flchangeList.getWidth(),new ArrayList<>(Arrays.asList("寿命已到","损坏","测试低良","新增测试站")), ivchangeArrow, (ty, i) -> {
                        tvchangeType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivchangeArrow);
                codePop_change.showAsDropDown(flchangeList, 0, 0);
            }
        });

        //测试片新旧程度
        flOldList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (codePop_old != null) {
                    if (codePop_old.isShowing()) {
                        codePop_old.dismiss();
                    }
                } else {
                    codePop_old = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flOldList.getWidth(),new ArrayList<>(Arrays.asList("全新","二次使用")), ivOldArrow, (ty, i) -> {
                        tvOldType.setText(ty);

                    });
                }
                FreeApi_PopUtils.setArrowShow(ivOldArrow);
                codePop_old.showAsDropDown(flOldList, 0, 0);
            }
        });


    }

    @OnClick({R.id.tvBaseSubmit,R.id.tvFix,R.id.tvChange,R.id.ivshow})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                submit();
                break;
            case R.id.tvFix:
                one.setVisibility(View.VISIBLE);
                two.setVisibility(View.GONE);
                setViewStates(true);
                etTime.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()).toString());
                break;
            case R.id.tvChange:
                one.setVisibility(View.GONE);
                two.setVisibility(View.VISIBLE);
                setViewStates(false);
                etTime.setText(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()).toString());
                break;
            case R.id.ivshow:
                ivshow.setRotationY(180);
//                showDialogSelect(view);
                add();
                break;
        }
    }


    //    添加
    private void add() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MlotGoldFingerFixOrChangeActivity.this);
        builder.setTitle("请输入测试站/次数");
        //  加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(MlotGoldFingerFixOrChangeActivity.this).inflate(R.layout.size_input, null);
        builder.setView(view);
        final EditText size1 = view.findViewById(R.id.size1);
        final EditText size2 = view.findViewById(R.id.size2);
        final EditText size3 = view.findViewById(R.id.size3);
        final EditText size4 = view.findViewById(R.id.size4);
        final EditText size5 = view.findViewById(R.id.size5);
        final EditText size6 = view.findViewById(R.id.size6);
        final EditText size7 = view.findViewById(R.id.size7);
        final EditText size8 = view.findViewById(R.id.size8);

        List<EditText> sizes = new ArrayList<>();
        sizes.add(size1);
        sizes.add(size2);
        sizes.add(size3);
        sizes.add(size4);
        sizes.add(size5);
        sizes.add(size6);
        sizes.add(size7);
        sizes.add(size8);

//        设置取消键
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
//       设置确定键
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

                for(EditText ed :sizes){
                    if(StringUtils.isNotEmpty(ed.getText())){
//                        boolean b = Pattern.matches("^\\d+$",ed.getText());
//                        if(!b){
//                            showToast("只能输入数字，请检查!", false);
//                            return;
//                        }
                        SIZE += (ed.getHint().toString()+" : "+ed.getText()+",");
                    }
                }
                etnum.setText(SIZE);
            }
        });
        builder.show();
    }

    private void setViewStates(boolean states) {
        tvFix.setBackgroundColor(states ? getResources().getColor(R.color.free_ui_blue_sky_theme_color) : getResources().getColor(R.color.white));
        tvFix.setTextColor(states ? getResources().getColor(R.color.white) : getResources().getColor(R.color.black));
        tvChange.setBackgroundColor(states ? getResources().getColor(R.color.white) : getResources().getColor(R.color.free_ui_blue_sky_theme_color) );
        tvChange.setTextColor(states ? getResources().getColor(R.color.black) : getResources().getColor(R.color.white));
        this.status = states;
    }

    private void submit(){

        if(getText(etUserName).equals("") || getText(eteqp).equals("")){
            showToast("必须信息不能为空", false);
            return;
        }

        if(one.getVisibility() == View.VISIBLE){
            if(tvWhereType.getText().equals("") || tvStepNameType.getText().equals("") || tvResonType.getText().equals("") || tvdoType.getText().equals("") || etTime.getText().equals("")){
                showToast("必须信息不能为空", false);
                return;
            }
            // 整数或小数
            String regex = "^\\d+(\\.\\d+)?|\\.\\d+$";
               boolean b = Pattern.matches(regex,ettime.getText());
               if(!b){
                   showToast("所用时长格式错误，请检查!", false);
                   return;
               }
        }else{
            if(tvMmtType.getText().equals("") || tvtypeType.getText().equals("") || tvchangeType.getText().equals("") || getText(etnum).equals("")){
                showToast("必须信息不能为空", false);
                return;
            }
            // 只能正整数
//            String regex = "^\\d+$";
//            boolean b = Pattern.matches(regex,etnum.getText());
//            if(!b){
//                showToast("当前簧片使用的次数格式错误，请检查!", false);
//                return;
//            }
        }

        FreeUI_EntityCallBack<BaseResponseBean<JSONObject>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<JSONObject>>
                (new TypeToken<BaseResponseBean<JSONObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JSONObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    clearAllInfo();
                    showToast("成功", true);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JSONObject>> response) {
                super.onError(response);
                loadError(response.getException(), "Gold_Finger_Fix");
            }
        };

        JsonObject map = new JsonObject();
            map.addProperty("EQUIPMENT", getText(eteqp).trim());
            map.addProperty("SENT_TIME", getText(etTime).trim());
            map.addProperty("USER_NAME", getText(etUserName).trim());
        if(one.getVisibility() == View.VISIBLE){
          map.addProperty("ACTIONTYPE", "GoldFinger_fix_info");
          map.addProperty("PLACE", tvWhereType.getText().toString().trim());
          map.addProperty("STATION", tvStepNameType.getText().toString().trim());
          map.addProperty("REASON", tvResonType.getText().toString().trim());
          map.addProperty("OPERATION", tvdoType.getText().toString().trim());
          map.addProperty("USER_TINE", getText(ettime).trim());
        }else{
            map.addProperty("ACTIONTYPE", "GoldFinger_change_info");
            map.addProperty("PLACE", tvMmtType.getText().toString().trim());
            map.addProperty("STATION", tvtypeType.getText().toString().trim());
            map.addProperty("REASON", tvchangeType.getText().toString().trim());
            map.addProperty("OPERATION", SIZE.substring(0,SIZE.trim().length()-1));
            map.addProperty("OLD", tvOldType.getText().toString().trim());
        }

        NetUtils.requestPostNet("IF.Gold_Finger_Fix", "Common", MlotGoldFingerFixOrChangeActivity.this, map, callBack);
    }

    private void showDialogSelect(View view){

        if(etnum != null){
            for (int i = 0; i < size.length; i++) {
                if(getText(etnum).contains(size[i])){
                    size_bool[i]=true;
                }
            }
        }

        AlertDialog.Builder aBuilder = new AlertDialog.Builder(MlotGoldFingerFixOrChangeActivity.this);
        aBuilder.setTitle("测试站/次数: ");
        // 创建多选对话框的内容
        aBuilder.setMultiChoiceItems(size, size_bool, new DialogInterface.OnMultiChoiceClickListener() {
            // 取消或勾选对话框内的单选框
            @Override
            public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                size_bool[i] = b;
            }
        });

        aBuilder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                // 获取勾选到的文本并打印
                String txt = "";
                for(short index=0;index<size_bool.length;++index){
                    if(size_bool[index]){
                        txt += (size[index]+" ");
                    }
                }
//                Log.d("选择操作工: ",size.toString());
                etnum.setText(txt);
                // 取消内部已勾选
                cancelBool();
            }
        });

        // 点击对话框外,进行取消对话框事件
        aBuilder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                // 取消内部已勾选
                cancelBool();
            }
        });

        aBuilder.show();
        etnum.setText(null);
    }
    // 取消内部已勾选
    private void cancelBool(){
        for(short index=0;index<size.length;++index){
            size_bool[index] = false;
        }
    }

    private void clearAllInfo(){
        etUserName.setText(null);
        eteqp.setText(null);
        tvWhereType.setTag(null);
        tvStepNameType.setText(null);
        tvResonType.setText(null);
        tvdoType.setText(null);
        ettime.setText(null);
        tvMmtType.setText(null);
        tvtypeType.setText(null);
        tvchangeType.setText(null);
        etnum.setText(null);
        tvOldType.setText(null);
    }

    @Override
    protected void initData() {

    }
}